import mysql, { Pool, PoolOptions } from 'mysql2/promise';

const dbConfig: PoolOptions = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
};

// 创建全局连接池
let pool: Pool | null = null;

export function initializePool(): void {
  if (!pool) {
    pool = mysql.createPool(dbConfig);
  }
}

export function getPool(): Pool {
  if (!pool) {
    throw new Error('Database pool has not been initialized. Call initializePool first.');
  }
  return pool;
}

// 关闭连接池
export async function closePool(): Promise<void> {
  if (pool) {
    await pool.end();
    pool = null;
  }
}
